package com.ken.server;

import com.ken.fx.BigModelNew;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/fx/websocket")
@Component
public class WebSocketServer {
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>(); // 会话映射

    @OnOpen
    public void onOpen(Session session) {
        // 假设您有某种方式来识别前端，这里简单以sessionId为例
        String identifier = session.getId();
        sessionMap.put(identifier, session);
        System.out.println("WebSocket连接开启：" + identifier);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        // 当前端发送消息时，这个方法会被调用
        BigModelNew bigModelNew = new BigModelNew(session.getId(), false);
        bigModelNew.startWork(session, message);
        // System.out.println("接收到消息: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        String identifier = session.getId();
        sessionMap.remove(identifier);
        // 清空该用户的历史记录
        BigModelNew bigModelNew = new BigModelNew(identifier, true);
        bigModelNew.clearUserHistory(identifier);
        System.out.println("WebSocket连接关闭：" + identifier);
    }
}
